﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace VitCode.Castle.Helper
{
    [StructLayout(LayoutKind.Sequential)]
    //这个类用于读写加密狗。
    public class Dog
    {
        public uint DogBytes, DogAddr;  //设置加密狗起始地址
        public byte[] DogData;  //设置数据的长度
        private int Retcode;

        [DllImport("Win32dll.dll", CharSet = CharSet.Ansi)]
        private static unsafe extern int DogRead(uint idogBytes, uint idogAddr, byte* pdogData);
        [DllImport("Win32dll.dll", CharSet = CharSet.Ansi)]
        private static unsafe extern int DogWrite(uint idogBytes, uint idogAddr, byte* pdogData);

        public unsafe Dog(ushort num)
        {
            DogBytes = num;
            DogData = new byte[DogBytes]; //设置数据的长度
        }

        public unsafe int ReadDog()
        {
            int result = 1;
            fixed (byte* pDogData = &DogData[0])
            {
                Retcode = DogRead(DogBytes, DogAddr, pDogData);　　//将数据读出加密狗
                if(Retcode == 0)
                {
                    var value = Encoding.Default.GetChars(DogData);
                    var str = new String(value);
                    if (str.Trim().Contains("VITCODEAMS"))
                        result = 0;
                }
                
            }
            return result;
        }
        public unsafe void WriteDog()
        {
            fixed (byte* pDogData = &DogData[0])
            {
                Retcode = DogWrite(DogBytes, DogAddr, pDogData);　//将资料写入加密狗
            }
        }
    }
}
